package com.linkhub.oms.admin.modules.invoice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.linkhub.oms.admin.common.exception.ExceptionFactory;
import com.linkhub.oms.admin.modules.invoice.domain.param.InvoiceGenerateParam;
import com.linkhub.oms.admin.modules.invoice.domain.param.InvoiceQueryParam;
import com.linkhub.oms.admin.modules.invoice.domain.vo.InvoiceGenerateVO;
import com.linkhub.oms.admin.modules.invoice.domain.vo.InvoiceListSqlResultVO;
import com.linkhub.oms.admin.modules.invoice.domain.vo.InvoiceListVO;
import com.linkhub.oms.admin.modules.invoice.service.InvoiceBizService;
import com.linkhub.oms.common.enums.mp.ExpenseTypeEnum;
import com.linkhub.oms.common.enums.mp.TransactionTypeEnum;
import com.linkhub.oms.common.response.PageDTO;
import com.linkhub.oms.component.mp.util.QtMybatisPlusUtil;
import com.linkhub.oms.component.mp.wrapper.WrapperConverter;
import com.linkhub.oms.dao.mapper.BillListEntityMapper;
import com.linkhub.oms.dao.mapper.UserAccountFlowEntityMapper;
import com.linkhub.oms.dao.mpservice.IBillListService;
import com.linkhub.oms.dao.mpservice.ICompanyService;
import com.linkhub.oms.dao.mpservice.IUserService;
import com.linkhub.oms.entity.BillListEntity;
import com.linkhub.oms.entity.CompanyEntity;
import com.linkhub.oms.entity.UserAccountFlowEntity;
import com.linkhub.oms.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Jaycle
 * @version 1.0.0
 * @Description InvoiceBizServiceImpl.java
 * @createTime 2024/06/30 23:00
 */
@Slf4j
@Service
public class InvoiceBizServiceImpl implements InvoiceBizService {

    @Resource
    private IUserService userService;

    @Resource
    private ICompanyService companyService;

    @Resource
    private IBillListService billListService;

    @Resource
    private BillListEntityMapper billListEntityMapper;

    @Resource
    private UserAccountFlowEntityMapper userAccountFlowEntityMapper;

    @Override
    public PageDTO<InvoiceListVO> listInvoices( InvoiceQueryParam invoiceQueryParam ) {

        String merchantUserId = invoiceQueryParam.getMerchantUserId();
        String merchantUserName = invoiceQueryParam.getMerchantUserName();

        MPJLambdaWrapper<BillListEntity> lambdaWrapper = JoinWrappers.lambda(BillListEntity.class);
        lambdaWrapper.select(BillListEntity::getInvoiceId,
                        BillListEntity::getMerchantUserId,
                        BillListEntity::getFee,
                        BillListEntity::getInvoiceDate,
                        BillListEntity::getStartDate,
                        BillListEntity::getEndDate)
                .selectAs(UserEntity::getUserName, InvoiceListVO::getMerchantUserName)
                .select(UserEntity::getUserName)
                .eq(invoiceQueryParam.isCustomRoleFlag(), BillListEntity::getMerchantUserId, invoiceQueryParam.getUserId())
                .eq(StringUtils.isNotBlank(merchantUserId), BillListEntity::getMerchantUserId, merchantUserId)
                .leftJoin(UserEntity.class, on -> on.eq(UserEntity::getUserId, BillListEntity::getMerchantUserId))
                .eq(StringUtils.isNotBlank(merchantUserName), UserEntity::getUserName, merchantUserName);

        lambdaWrapper.orderByDesc(BillListEntity::getMerchantUserId, BillListEntity::getInvoiceDate).page(new Page<>(invoiceQueryParam.getPage(), invoiceQueryParam.getSize()));

        Page<InvoiceListSqlResultVO> objectPage = new Page<>(invoiceQueryParam.getPage(), invoiceQueryParam.getSize());
        objectPage.setOptimizeJoinOfCountSql(false);
        Page<InvoiceListSqlResultVO> page = billListEntityMapper.selectJoinPage(objectPage, InvoiceListSqlResultVO.class, lambdaWrapper);

        return QtMybatisPlusUtil.convertPage(page, this::convert);
    }

    private InvoiceListVO convert( InvoiceListSqlResultVO invoiceListVO ) {
        InvoiceListVO vo = new InvoiceListVO();
        BeanUtil.copyProperties(invoiceListVO, vo);
        vo.setBillingCycle(invoiceListVO.getStartDate() + " To " + invoiceListVO.getEndDate());
        return vo;
    }

    @Override
    public InvoiceGenerateVO generateInvoices( InvoiceGenerateParam invoiceGenerateParam ) {
        String userId = invoiceGenerateParam.getMerchantUserId();
        String invoiceId = invoiceGenerateParam.getInvoiceId();
        InvoiceGenerateVO invoiceGenerateVO = new InvoiceGenerateVO();
        BillListEntity billListEntity = billListService.getInvoiceRecord(userId, invoiceId);
        if (billListEntity == null) {
            return invoiceGenerateVO;
        }
        final String startDate = billListEntity.getStartDate();
        final String endDate = billListEntity.getEndDate();
        invoiceGenerateVO.setInvoiceId(billListEntity.getInvoiceId());
        invoiceGenerateVO.setStartDate(startDate);
        invoiceGenerateVO.setEndDate(endDate);
        invoiceGenerateVO.setSumFee(billListEntity.getFee());

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate dateTime = LocalDate.parse(endDate, formatter);
        LocalDate nextEndDate = dateTime.plusDays(1);
        LambdaQueryWrapper<UserAccountFlowEntity> lambdaQuery = Wrappers.lambdaQuery(UserAccountFlowEntity.class);
        lambdaQuery.select(UserAccountFlowEntity::getExpenseType,
                        UserAccountFlowEntity::getAmount)
                .eq(UserAccountFlowEntity::getUserId, userId)
                .eq(UserAccountFlowEntity::getTransactionType, TransactionTypeEnum.PAY)
                .ge(UserAccountFlowEntity::getCreatedTime, startDate)
                .lt(UserAccountFlowEntity::getCreatedTime, nextEndDate)
                .groupBy(UserAccountFlowEntity::getExpenseType);
        QueryWrapper<UserAccountFlowEntity> queryWrapper = WrapperConverter.convertLambdaCondition(lambdaQuery);
        queryWrapper.select("Fexpense_type AS expenseType, SUM(Famount) AS amount");

        List<UserAccountFlowEntity> resultList = userAccountFlowEntityMapper.selectList(queryWrapper);
        Map<ExpenseTypeEnum, BigDecimal> variousFeeMap = resultList.stream()
                .collect(Collectors.toMap(
                        UserAccountFlowEntity::getExpenseType,
                        UserAccountFlowEntity::getAmount
                ));
        BigDecimal currentSumFee = variousFeeMap.values().stream()
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        if (!new BigDecimal(billListEntity.getFee()).equals(currentSumFee)) {
            throw ExceptionFactory.getI18nBizException("invoice.details.fee.problem");
        }

        final BigDecimal defaultFee = new BigDecimal("0");
        invoiceGenerateVO.setFreight(String.valueOf(variousFeeMap.getOrDefault(ExpenseTypeEnum.FREIGHT, defaultFee)));
        invoiceGenerateVO.setProcessingFee(String.valueOf(variousFeeMap.getOrDefault(ExpenseTypeEnum.PROCESSING, defaultFee)));
        invoiceGenerateVO.setHandlingFee(String.valueOf(variousFeeMap.getOrDefault(ExpenseTypeEnum.OPERATE, defaultFee)));
        invoiceGenerateVO.setStorageFee(String.valueOf(variousFeeMap.getOrDefault(ExpenseTypeEnum.STORAGE, defaultFee)));
        invoiceGenerateVO.setDeliveryTakingFee(String.valueOf(variousFeeMap.getOrDefault(ExpenseTypeEnum.PICK_UP_ORDER, defaultFee)));
        invoiceGenerateVO.setVatHandlingFee(String.valueOf(variousFeeMap.getOrDefault(ExpenseTypeEnum.VAT_HANDLING_FEE, defaultFee)));
        invoiceGenerateVO.setVatFee(String.valueOf(variousFeeMap.getOrDefault(ExpenseTypeEnum.VAT, defaultFee)));
        invoiceGenerateVO.setRegistrationFee(String.valueOf(variousFeeMap.getOrDefault(ExpenseTypeEnum.REGISTRATION_FEE, defaultFee)));

        UserEntity user = userService.getUserByUserId(userId);
        invoiceGenerateVO.setEmail(user.getEmail());

        CompanyEntity company = companyService.getByUserId(userId);
        invoiceGenerateVO.setInvoiceAddress(company == null ? "" : company.getAddress());

        return invoiceGenerateVO;
    }

}
